package com.authine.cloudpivot.web.api.service.impl;

import com.authine.cloudpivot.engine.api.model.bizmodel.BizSchemaModel;
import com.authine.cloudpivot.engine.api.model.runtime.BizObjectModel;
import com.authine.cloudpivot.engine.api.model.runtime.BizObjectQueryModel;
import com.authine.cloudpivot.engine.api.model.runtime.SelectionValue;
import com.authine.cloudpivot.engine.component.query.api.FilterExpression;
import com.authine.cloudpivot.engine.component.query.api.Page;
import com.authine.cloudpivot.engine.component.query.api.helper.PageableImpl;
import com.authine.cloudpivot.engine.component.query.api.helper.Q;
import com.authine.cloudpivot.engine.enums.type.QueryDisplayType;
import com.authine.cloudpivot.web.api.dao.KHXXMapper;
import com.authine.cloudpivot.web.api.dao.UserMapper;
import com.authine.cloudpivot.web.api.domain.Constants;
import com.authine.cloudpivot.web.api.domain.dto.CustomerDTO;
import com.authine.cloudpivot.web.api.dubbo.DubboConfigService;
import com.authine.cloudpivot.web.api.exception.PortalException;
import com.authine.cloudpivot.web.api.service.CustomerService;
import com.authine.cloudpivot.web.api.vo.KHXX;
import com.authine.cloudpivot.web.api.vo.User;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.math.BigDecimal;
import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.*;


@Slf4j
@Service
public class CustomerServiceImpl implements CustomerService {

    @Autowired
    private KHXXMapper khxxMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private FescoadQueryServiceImpl fescoadQueryServiceImpl;

    @Autowired
    private DubboConfigService dubboConfigService;

    /**
     * @Description : 生成客户信息
     * @param ： customerDTO
     * @author : Liun
     * @date : 2020/4/30
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public  void customerInformation(List<CustomerDTO> customerDTOS) throws PortalException{

        SimpleDateFormat sf =new SimpleDateFormat("yyyy-MM-dd 00:00:00");
        String nowTime=sf.format(new Date());
        Date nowDate = sf.parse(nowTime,new ParsePosition(0));

        //推送AccountFile待办
        String  url = "form/detail?schemaCode=AccountFiles&sheetCode=AccountFiles";
        String content="AccountFile";
        String  title;
        for(CustomerDTO customerDTO:customerDTOS){
            String createDate=customerDTO.getCreateDate()+" 00:00:00";
            Date createdate = sf.parse(createDate,new ParsePosition(0));
            String uuid  = UUID.randomUUID().toString().replace("-","");
            //获取项目经理信息
            User user= userMapper.getUserInfo(customerDTO.getCustomerService(),customerDTO.getCustomerEmail());
            if(ObjectUtils.allNotNull(user)){
                Example example=new Example(KHXX.class);
                Example.Criteria criteria= example.createCriteria();
                criteria.andEqualTo("customercode",customerDTO.getCustomerCode());
                KHXX khxxExist=khxxMapper.selectOneByExample(example);
                //客户信息存在则修改，否则进行新增
                if(ObjectUtils.allNotNull(khxxExist)){
                    khxxExist=this.setKHXXValue(khxxExist,user,customerDTO,nowDate,createdate);
                    khxxMapper.updateCustomer(khxxExist);
                    updateProjectInfo(khxxExist);
                }else{
                    KHXX khxx=new KHXX();
                    khxx.setId(uuid);
                    khxx.setCreatedtime(nowDate);
                    khxx=this.setKHXXValue(khxx,user,customerDTO,nowDate,createdate);
                    khxxMapper.createCustomer(khxx);
                    //新增完成客户信息给对应的项目经理推送填写account file的通知
                    title="请为《"+khxx.getName()+"》新增AccountFile";
                    //fescoadQueryServiceImpl.sendMessage("1220692228674564", url,content,title);
                }
            }
        }
    }

    private void updateProjectInfo(KHXX khxxExist) {
        String  id = khxxExist.getId();
        //招聘需求变更信息
        BizObjectQueryModel queryModel = new BizObjectQueryModel();
        PageableImpl pageable = new PageableImpl(0, 9999);
        queryModel.setSchemaCode("XMQD");
        queryModel.setQueryCode("XMQD");
        queryModel.setPageable(pageable);
        FilterExpression filterExpression = Q.it("customName", FilterExpression.Op.Eq, id);
        queryModel.setFilterExpr(filterExpression);
        BizObjectQueryModel.Options option = new BizObjectQueryModel.Options();
        option.setQueryDisplayType(QueryDisplayType.APPEND);
        option.setCustomDisplayColumns(Arrays.asList("id","subjectStartTime","subjectEndTime","creater","name","projectNames"));
        queryModel.setOptions(option);
        List<? extends BizObjectModel> content = dubboConfigService.getBizObjectFacade().queryBizObjects(queryModel).getContent();
        for(int i=0; i<content.size(); i++){
            BizObjectModel xmObjectModel = content.get(i);
            Map<String, Object> xmData = xmObjectModel.getData();
            if(xmData.get("subjectEndTime") == null || ((Date)xmData.get("subjectEndTime")).before(khxxExist.getContractEndDate())){
                xmObjectModel.put("subjectStartTime", khxxExist.getContractStartDate());
                xmObjectModel.put("subjectEndTime", khxxExist.getContractEndDate());
                SelectionValue user = ((ArrayList<SelectionValue>) xmData.get("creater")).get(0);
                String projectId = xmData.get("id").toString();
                BizSchemaModel bizSchemaModel = dubboConfigService.getAppManagementFacade().getBizSchemaBySchemaCode("XMQD");
                dubboConfigService.getBizObjectFacade().updateBizObjectModel(user.getId(), xmObjectModel, bizSchemaModel);
                //招聘
                BizObjectQueryModel zpQueryModel = new BizObjectQueryModel();
                zpQueryModel.setSchemaCode("recruitmentDemand");
                zpQueryModel.setQueryCode("recruitmentDemand");
                zpQueryModel.setPageable(pageable);
                FilterExpression idfilterExpression = Q.it("projectName", FilterExpression.Op.Eq, projectId);
                FilterExpression typeFilterExpression = Q.it("recruitmentType", FilterExpression.Op.Eq, "不确定人数");
                FilterExpression filter = Q.and(Arrays.asList(idfilterExpression,typeFilterExpression));
                zpQueryModel.setFilterExpr(filter);
                BizObjectQueryModel.Options zpOption = new BizObjectQueryModel.Options();
                zpOption.setQueryDisplayType(QueryDisplayType.APPEND);
                zpOption.setCustomDisplayColumns(Arrays.asList("id","creater","name","recruitmentType","demandEndTime","demandReceiver","postJDStr","projectNameStr","operator"));
                zpQueryModel.setOptions(zpOption);
                List<? extends BizObjectModel> zpContent = dubboConfigService.getBizObjectFacade().queryBizObjects(zpQueryModel).getContent();
                for(int j=0; i<zpContent.size(); j++){
                    BizObjectModel zpObjectModel = zpContent.get(i);
                    Map<String, Object> zpData = zpObjectModel.getData();
                    if((zpData.get("subjectEndTime") != null && ((Date)zpData.get("demandEndTime")).after(khxxExist.getContractEndDate()))){
                        zpObjectModel.put("demandEndTime", khxxExist.getContractEndDate());
                        SelectionValue creater = ((ArrayList<SelectionValue>) xmData.get("creater")).get(0);
                        BizSchemaModel zpBizSchemaModel = dubboConfigService.getAppManagementFacade().getBizSchemaBySchemaCode("recruitmentDemand");
                        dubboConfigService.getBizObjectFacade().updateBizObjectModel(creater.getId(), zpObjectModel, zpBizSchemaModel);
                    }
                }
            }
        }
    }

    /**
     * @Description : 设置客户信息值
     * @param ： khxx
     * @param ： user
     * @param ： customerDTO
     * @param ： nowDate
     * @author : Liun
     * @date : 2020/5/6
     */
    public KHXX setKHXXValue(KHXX khxx,User user,CustomerDTO customerDTO,Date nowDate,Date createdate){
        //系统信息
        khxx.setName("客户信息-"+customerDTO.getCustomerName());
        khxx.setCreater(user.getId());
        khxx.setCreateddeptid(user.getDepartmentId());
        khxx.setOwner(user.getId());
        khxx.setOwnerdeptid(user.getDepartmentId());
        khxx.setModifier(user.getId());
        khxx.setModifiedtime(nowDate);
        khxx.setSequencestatus(Constants.COMPLETED);
        //客户信息
        khxx.setGroupname(customerDTO.getGroupName());
        khxx.setGroupno(customerDTO.getGroupNo());
        khxx.setCustomername(customerDTO.getCustomerName());
        khxx.setCustomercode(customerDTO.getCustomerCode());
        khxx.setCustomerstate(customerDTO.getCustomerState());
        khxx.setCustomershortname(customerDTO.getCustomerShortName());
        khxx.setServicenum(new BigDecimal(customerDTO.getServiceNum()));
        khxx.setCustomerservice(customerDTO.getCustomerService());
        khxx.setCustomeremail(customerDTO.getCustomerEmail());
        khxx.setDepartment(customerDTO.getDepartment());
        khxx.setCustomerprofile(customerDTO.getCustomerProfile());
        khxx.setCreatedate(createdate);

        khxx.setLegalEntityName(customerDTO.getLegalEntityName());
        khxx.setLegalEntityCode(customerDTO.getLegalEntityCode());

        SimpleDateFormat sf =new SimpleDateFormat("yyyy-MM-dd 00:00:00");
        String contractStart = customerDTO.getContractStartDate() +" 00:00:00";
        Date contractStartDate = sf.parse(contractStart,new ParsePosition(0));
        khxx.setContractStartDate(contractStartDate);
        String contractEnd = customerDTO.getContractEndDate() +" 00:00:00";
        Date contractEndDate = sf.parse(contractEnd,new ParsePosition(0));
        khxx.setContractEndDate(contractEndDate);
        //联系人信息
        khxx.setContacttype(customerDTO.getContactType());
        khxx.setContactname(customerDTO.getContactName());
        khxx.setBirthday(customerDTO.getBirthday());
        khxx.setEmail(customerDTO.getEmail());
        khxx.setRank(customerDTO.getRank());
        khxx.setPosition(customerDTO.getPosition());
        khxx.setLandline(customerDTO.getLandline());
        khxx.setMobile(customerDTO.getMobile());
        khxx.setPostalcode(customerDTO.getPostalCode());
        khxx.setContactaddress(customerDTO.getContactAddress());
        khxx.setDept(customerDTO.getDept());
        khxx.setSuperior(customerDTO.getSuperior());
        khxx.setNotes(customerDTO.getNotes());
        return khxx;
    }
}